package com.faceidentify

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.hardware.usb.UsbManager
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Base64
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.JsonObject
import com.zkteco.android.IDReader.IDPhotoHelper.Bgr2Bitmap
import com.zkteco.android.IDReader.WLTService
import com.zkteco.android.biometric.core.device.ParameterHelper
import com.zkteco.android.biometric.core.device.TransportType
import com.zkteco.android.biometric.core.utils.LogHelper
import com.zkteco.android.biometric.module.idcard.IDCardReader
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.*

class IdentifyRegisterActivty : AppCompatActivity() {
    //请求权限
    private var VID = 1024 //IDR VID

    private var PID = 50010 //IDR PID

    private var ACTION_USB_PERMISSION = "com.zkteco.biometric.idrdemo.USB_PERMISSION"

    private var registerurl = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=24.75fe8070f1bf141733dfbb61b7d9357e.2592000.1626751148.282335-23997882"

    //身份证相关变量
    var bStart = false

    private var idCardReader: IDCardReader? = null

    private var idcardImg: ImageView? = null
    private var idcardTxt: TextView? = null
    private var txtCardType: TextView? = null
    private var txtName: TextView? = null
    private var txtNation: TextView? = null
    private var txtBorn: TextView? = null
    private var txtID: TextView? = null
    private var txtAddr: TextView? = null

    private var httpHelper: HttpHelper? = null

    private var mContext: Context? = null

    private var achieveInfo: Button? = null
    private var registerInfo: Button? = null

    private var uri: Uri? = null
    private var mediaPlayer: MediaPlayer? = null

    private var registerName: String? = null
    private var bitmapBase64Str: String? = null


    @SuppressLint("HandlerLeak")
    private var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            if (msg.what == 1) {
                OnBnOpen()
                startVoice()
            }

            if (msg.what == 2) {
                startVoice()
            }

            if (msg.what == 3) {
                finish()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_identify_register)
        mContext = this
        initView()
        initEvent()

    }

    override fun onStart() {
        super.onStart()
        requestPermission()
        handler.sendEmptyMessageDelayed(1, 3000)
    }

    private fun initView() {
        httpHelper = HttpHelper.getInstance()
        mediaPlayer = MediaPlayer()

        idcardImg = findViewById<View>(R.id.idcardImg) as ImageView?
        idcardTxt = findViewById<View>(R.id.idcardTxt) as TextView?

        txtName = findViewById<View>(R.id.txtName) as TextView?
        txtNation = findViewById<View>(R.id.txtNation) as TextView?
        txtBorn = findViewById<View>(R.id.txtBorn) as TextView?
        txtID = findViewById<View>(R.id.txtID) as TextView?
        txtAddr = findViewById<View>(R.id.txtAddr) as TextView?
        achieveInfo = findViewById<View>(R.id.achieve_info) as Button?
        registerInfo = findViewById<View>(R.id.register_info) as Button?
    }

    private fun initEvent() {
        achieveInfo!!.setOnClickListener { OnBnReadOnBnRead() }
        registerInfo!!.setOnClickListener { registerInfo(registerName, bitmapBase64Str) }
    }

    private fun registerInfo(registerName: String?, bitmapBase64Str: String?) {
        val jsonObject = JsonObject()
        jsonObject.addProperty("image", bitmapBase64Str)
        jsonObject.addProperty("image_type", "BASE64")
        jsonObject.addProperty("group_id", "2021_6_20_group1")
        jsonObject.addProperty("user_id", "Face1")
        jsonObject.addProperty("user_info", registerName)
        jsonObject.addProperty("quality_control", "NORMAL")

        httpHelper!!.postJsonObject(registerurl, jsonObject, object : ResponseListener {
            override fun doAction(jsonObject: JsonObject?) {
                idcardTxt!!.text = "身份注册已完毕,即将回到主页面"
                startVoice()
                handler.sendEmptyMessageDelayed(3, 5000)
            }
        })
    }





    //读取身份证开启权限方法
    private fun requestPermission() {
        val usbManager = this.getSystemService(Context.USB_SERVICE) as UsbManager
        for (device in usbManager.deviceList.values) {
            if (device.vendorId == VID && device.productId == PID) {
                val intent = Intent(ACTION_USB_PERMISSION)
                val pendingIntent = PendingIntent.getBroadcast(this.applicationContext, 0, intent, 0)
                usbManager.requestPermission(device, pendingIntent)
            }
        }
    }

    //打开身份证设备连接
    private fun OnBnOpen() {
        if (bStart) {
            Toast.makeText(mContext,"设备已连接",Toast.LENGTH_SHORT)
            return
        }
        startIDCardReader()
        try {
            idCardReader!!.open(0)
            bStart = true
            Toast.makeText(mContext,"设备连接成功",Toast.LENGTH_SHORT)

        } catch (e: IDCardReaderException) {
            e.printStackTrace()
            Toast.makeText(mContext,"设备连接失败",Toast.LENGTH_SHORT)

            IDCardReaderFactory.destroy(idCardReader)
            idCardReader = null
        }
    }


    private fun resetContent() {
        idcardImg!!.setImageBitmap(null)
        idcardTxt!!.text = null
        txtName!!.text = null
        txtNation!!.text = null
        txtBorn!!.text = null
        txtID!!.text = null
        txtAddr!!.text = null
    }

    //读取身份证数据
    private fun OnBnReadOnBnRead() {
        if (!bStart) {
            Toast.makeText(mContext,"请先连接设备",Toast.LENGTH_SHORT)

            return
        }
        resetContent()
        try {
            idCardReader!!.findCard(0)
            idCardReader!!.selectCard(0)
        } catch (e: IDCardReaderException) {
            e.printStackTrace()
        }

        try {
            val ret = idCardReader!!.readCardEx(0, 1)
            if (1 == ret) {
                val idCardInfo = idCardReader!!.lastIDCardInfo
                txtName!!.text = idCardInfo.name.substring(0, 1) + "**"
                //                txtCardType.setText(idCardInfo.);
                txtNation!!.text = idCardInfo.nation
                txtBorn!!.text = idCardInfo.birth.substring(0, 4) + "****"
                txtID!!.text = idCardInfo.id.substring(0, 3) + "***************"
                txtAddr!!.text = idCardInfo.address.substring(0, 5) + "******************************"
                if (idCardInfo.photolength > 0) {
                    val buf = ByteArray(WLTService.imgLength)
                    if (1 == WLTService.wlt2Bmp(idCardInfo.photo, buf)) {
                        var bitmap = Bgr2Bitmap(buf)

                        idcardImg!!.setImageBitmap(bitmap)
                        registerName = idCardInfo.name
                        bitmapBase64Str = bitmapToBase64(bitmap)

                        if (!TextUtils.isEmpty(registerName) && !TextUtils.isEmpty(bitmapBase64Str)) {
                            idcardTxt!!.text = "身份读取成功"
                        } else {
                            idcardTxt!!.text = "身份读取失败"
                        }

                        handler.sendEmptyMessageDelayed(2, 2000)
                    }
                }
            }
        } catch (e: IDCardReaderException) {
            e.printStackTrace()
            Toast.makeText(mContext,"读卡失败",Toast.LENGTH_SHORT)

        }
    }


    private fun startIDCardReader() {
        LogHelper.setLevel(Log.VERBOSE)
        val idrparams: MutableMap<String, Int> = HashMap<String, Int>()
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID)
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID)
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams as MutableMap<String, Any>?)

    }

    //语音播报
    private fun startVoice() {
        mediaPlayer!!.reset()
        uri = Uri.parse("https://tsn.baidu.com/text2audio?tex=" + idcardTxt!!.text.toString().trim { it <= ' ' } + "&lan=zh&cuid=10.0.19042.1052&ctp=1&tok=24.902233477ec4f5c7a7ae535c3c763813.2592000.1626685339.282335-24368715&audio=3")

        try {
            mediaPlayer!!.setDataSource(applicationContext, uri!!)
            mediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC)
            mediaPlayer!!.prepareAsync()
            mediaPlayer!!.setOnPreparedListener { mediaPlayer!!.start() }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun bitmapToBase64(bitmap: Bitmap?): String? {
        var result: String? = null
        var baos: ByteArrayOutputStream? = null
        try {
            if (bitmap != null) {
                baos = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                baos.flush()
                baos.close()
                val bitmapBytes = baos.toByteArray()
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                if (baos != null) {
                    baos.flush()
                    baos.close()
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return result
    }


}